/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-10-10 09:40:00
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-10-09 21:40:08
 * @FilePath: \work-tool\my-dev-project\src\views\system\department.tsx
 * @Description: 部门管理页面
 */
import React, { useState, useEffect } from 'react';
import { Card, Tree, Button, Input, Modal, Form, Select, message, Space, Table } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import type { ColumnsType } from 'antd/es/table';

const { TextArea } = Input;
const { Option } = Select;
const { confirm } = Modal;

// 模拟部门数据
const mockDepartments = [
  {
    id: '1',
    name: '总公司',
    code: 'HEAD_OFFICE',
    description: '公司总部',
    parentId: '0',
    order: 1,
    status: 'active',
    createTime: '2025-01-01',
    userCount: 50
  },
  {
    id: '2',
    name: '技术部',
    code: 'TECH_DEPT',
    description: '负责产品研发和技术支持',
    parentId: '1',
    order: 1,
    status: 'active',
    createTime: '2025-01-02',
    userCount: 20
  },
  {
    id: '3',
    name: '产品部',
    code: 'PRODUCT_DEPT',
    description: '负责产品规划和设计',
    parentId: '1',
    order: 2,
    status: 'active',
    createTime: '2025-01-02',
    userCount: 10
  },
  {
    id: '4',
    name: '市场部',
    code: 'MARKET_DEPT',
    description: '负责市场推广和销售',
    parentId: '1',
    order: 3,
    status: 'active',
    createTime: '2025-01-02',
    userCount: 15
  },
  {
    id: '5',
    name: '前端开发组',
    code: 'FRONTEND_GROUP',
    description: '负责前端开发工作',
    parentId: '2',
    order: 1,
    status: 'active',
    createTime: '2025-01-03',
    userCount: 8
  },
  {
    id: '6',
    name: '后端开发组',
    code: 'BACKEND_GROUP',
    description: '负责后端开发工作',
    parentId: '2',
    order: 2,
    status: 'active',
    createTime: '2025-01-03',
    userCount: 10
  },
  {
    id: '7',
    name: '测试组',
    code: 'TEST_GROUP',
    description: '负责软件测试工作',
    parentId: '2',
    order: 3,
    status: 'active',
    createTime: '2025-01-03',
    userCount: 2
  },
];

interface Department {
  id: string;
  name: string;
  code: string;
  description: string;
  parentId: string;
  order: number;
  status: string;
  createTime: string;
  userCount: number;
}

const DepartmentManagement: React.FC = () => {
  const [departments, setDepartments] = useState<Department[]>(mockDepartments);
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [editingDepartment, setEditingDepartment] = useState<Department | null>(null);
  const [form] = Form.useForm();
  const [showUserCount, setShowUserCount] = useState<boolean>(false);

  // 构建树形数据
  const buildTreeData = (deptItems: Department[]): DataNode[] => {
    const roots = deptItems.filter(item => item.parentId === '0');
    const buildChildren = (parentId: string): DataNode[] => {
      return deptItems
        .filter(item => item.parentId === parentId)
        .sort((a, b) => a.order - b.order)
        .map(item => ({
          title: showUserCount
            ? `${item.name} (${item.userCount}人)`
            : item.name,
          key: item.id,
          children: buildChildren(item.id),
          isLeaf: deptItems.filter(d => d.parentId === item.id).length === 0,
        }));
    };

    return roots
      .sort((a, b) => a.order - b.order)
      .map(item => ({
        title: showUserCount
          ? `${item.name} (${item.userCount}人)`
          : item.name,
        key: item.id,
        children: buildChildren(item.id),
        isLeaf: deptItems.filter(d => d.parentId === item.id).length === 0,
      }));
  };

  // 获取父级部门选项
  const getParentDepartmentOptions = (): { label: string; value: string }[] => {
    // 构建层级显示的部门名称
    const getHierarchicalName = (id: string, level = 0): string => {
      const dept = departments.find(item => item.id === id);
      if (!dept) return '';
      if (dept.parentId === '0') return dept.name;
      return `${'├─'.repeat(level)}${dept.name}`;
    };

    const options = departments
      .filter(item =>
        item.id !== editingDepartment?.id &&
        !isDescendantOf(editingDepartment?.id, item.id)
      )
      .map(item => ({
        label: getHierarchicalName(item.id, getLevel(item.id)),
        value: item.id
      }));
    return [{ label: '作为顶级部门', value: '0' }, ...options];
  };

  // 检查是否是子部门
  const isDescendantOf = (parentId: string | undefined, childId: string): boolean => {
    if (!parentId) return false;
    const child = departments.find(item => item.id === childId);
    if (!child) return false;
    if (child.parentId === parentId) return true;
    return isDescendantOf(parentId, child.parentId);
  };

  // 获取部门层级
  const getLevel = (id: string): number => {
    const dept = departments.find(item => item.id === id);
    if (!dept || dept.parentId === '0') return 0;
    return getLevel(dept.parentId) + 1;
  };

  useEffect(() => {
    setTreeData(buildTreeData(departments));
  }, [departments, showUserCount]);

  // 处理节点选择
  const onSelect = (selectedKeys: string[]) => {
    setSelectedKeys(selectedKeys);
  };

  // 打开创建/编辑模态框
  const showModal = (dept?: Department) => {
    if (dept) {
      setEditingDepartment(dept);
      form.setFieldsValue(dept);
    } else {
      setEditingDepartment(null);
      // 如果有选中的部门，默认设置为父部门
      const defaultParentId = selectedKeys.length > 0 ? selectedKeys[0] : '0';
      form.resetFields();
      form.setFieldsValue({ parentId: defaultParentId, order: 1, status: 'active' });
    }
    setIsModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        if (editingDepartment) {
          // 编辑部门
          const updatedDepartments = departments.map(dept =>
            dept.id === editingDepartment.id ? { ...dept, ...values } : dept
          );
          setDepartments(updatedDepartments);
          message.success('部门更新成功');
        } else {
          // 创建部门
          const newDepartment: Department = {
            ...values,
            id: `new_${Date.now()}`,
            createTime: new Date().toISOString().split('T')[0],
            userCount: 0,
          };
          setDepartments([...departments, newDepartment]);
          message.success('部门创建成功');
        }
        setIsModalVisible(false);
        form.resetFields();
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  // 删除部门
  const handleDelete = () => {
    if (!selectedKeys.length) {
      message.warning('请先选择要删除的部门');
      return;
    }

    const idToDelete = selectedKeys[0];
    // 检查是否有子部门
    const hasChildren = departments.some(item => item.parentId === idToDelete);

    // 检查是否有用户
    const hasUsers = departments.find(item => item.id === idToDelete)?.userCount || 0 > 0;

    if (hasChildren) {
      message.error('该部门下有子部门，无法删除');
      return;
    }

    if (hasUsers) {
      message.error('该部门下有用户，无法删除');
      return;
    }

    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除该部门吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        setDepartments(departments.filter(dept => dept.id !== idToDelete));
        setSelectedKeys([]);
        message.success('部门删除成功');
      },
    });
  };

  // 表格列配置（用于展示部门列表视图）
  const tableColumns: ColumnsType<Department> = [
    {
      title: '部门ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '部门名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      render: (name, record) => {
        const level = getLevel(record.id);
        return (
          <span style={{ paddingLeft: `${level * 20}px` }}>
            {level > 0 && '├─'} {name}
          </span>
        );
      },
    },
    {
      title: '部门编码',
      dataIndex: 'code',
      key: 'code',
      ellipsis: true,
    },
    {
      title: '部门描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '用户数量',
      dataIndex: 'userCount',
      key: 'userCount',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => (
        <span style={{
          color: status === 'active' ? 'green' : 'red',
          fontWeight: 'bold'
        }}>
          {status === 'active' ? '启用' : '禁用'}
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card
        title="部门管理"
        extra={
          <Space>
            <Button onClick={() => setShowUserCount(!showUserCount)}>
              {showUserCount ? '隐藏用户数' : '显示用户数'}
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
              添加部门
            </Button>
            <Button icon={<EditOutlined />} onClick={() => {
              if (selectedKeys.length) {
                const selectedDept = departments.find(item => item.id === selectedKeys[0]);
                if (selectedDept) showModal(selectedDept);
              } else {
                message.warning('请先选择要编辑的部门');
              }
            }}>
              编辑部门
            </Button>
            <Button danger icon={<DeleteOutlined />} onClick={handleDelete}>
              删除部门
            </Button>
          </Space>
        }
      >
        <div style={{ border: '1px solid #f0f0f0', borderRadius: '4px', padding: '16px', marginBottom: '20px' }}>
          <h4 style={{ marginBottom: '16px' }}>部门树结构</h4>
          <Tree
            className="department-tree"
            selectedKeys={selectedKeys}
            treeData={treeData}
            onSelect={onSelect}
          />
        </div>

        <h4 style={{ marginBottom: '16px' }}>部门列表</h4>
        <Table
          columns={tableColumns}
          dataSource={departments}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1200 }}
          onRow={(record) => ({
            onClick: () => setSelectedKeys([record.id]),
            className: selectedKeys.includes(record.id) ? 'ant-table-row-selected' : '',
          })}
        />
      </Card>

      {/* 创建/编辑部门模态框 */}
      <Modal
        title={editingDepartment ? "编辑部门" : "创建部门"}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={editingDepartment || {
            parentId: '0',
            order: 1,
            status: 'active'
          }}
        >
          <Form.Item
            name="parentId"
            label="上级部门"
            rules={[{ required: true, message: '请选择上级部门' }]}
          >
            <Select placeholder="请选择上级部门" allowClear>
              {getParentDepartmentOptions().map(option => (
                <Option key={option.value} value={option.value}>{option.label}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="name"
            label="部门名称"
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input placeholder="请输入部门名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="部门编码"
            rules={[
              { required: true, message: '请输入部门编码' },
              { pattern: /^[A-Z_]+$/, message: '部门编码只能包含大写字母和下划线' }
            ]}

          >
            <Input placeholder="请输入部门编码" disabled={!!editingDepartment} />
          </Form.Item>

          <Form.Item
            name="description"
            label="部门描述"
          >
            <TextArea rows={3} placeholder="请输入部门描述" />
          </Form.Item>

          <Form.Item
            name="order"
            label="排序号"
            rules={[
              { required: true, message: '请输入排序号' },
              { type: 'number', min: 1, message: '排序号必须大于0' }
            ]}
          >
            <Input type="number" placeholder="请输入排序号" min={1} />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">
                {editingDepartment ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DepartmentManagement;